package com.javafactroy.kunlong.base.context;


import app.support.context.DefaultRequestContextFactory;
import app.support.context.RequestContext;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Component
public class ApiContext implements ApplicationContextAware {
    public static ApiContext INST = new ApiContext();

    private static ApplicationContext appCtxt;


    public static ExecutorService EXECUTORS = Executors.newCachedThreadPool();

    public ApplicationContext getAppCtxt() {
        return appCtxt;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appCtxt = applicationContext;

    }

    public JdbcTemplate getJdbcTemplate(String name) {
        return appCtxt.getBean(name, JdbcTemplate.class);

    }

    public JdbcTemplate getMysqlJdbcTemplate() {
        return getJdbcTemplate("mysqlTemplate");

    }

    public SqlSessionFactory getSqlSessionFactory(String name) {
        return appCtxt.getBean(name, SqlSessionFactory.class);

    }

    public SqlSessionFactory getMysqlSessionFactory() {
        return getSqlSessionFactory("mysqlSessionFactroy");

    }

    /**
     * @return 当前请求上下文
     */
    public static RequestContext getContext() {
        return DefaultRequestContextFactory.getInstance().getRequestContext();
    }

    public static Object getAttribute(String key) {
        RequestContext ctx = getContext();
        if (ctx == null) {
            return null;
        }
        Object obj = ctx.getAttribute(key);
        if (obj == null) {
            return null;
        }
        return obj;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getAttribute(String key, Class<T> clazz) {
        Object obj = getAttribute(key);
        return obj == null ? null : (T) obj;
    }

    public static void setAttribute(String key, Object val) {
        RequestContext ctx = getContext();
        if (ctx == null) {
            ctx = DefaultRequestContextFactory.getInstance().create();
        }
        ctx.setAttribute(key, val);
    }

}